<template>
  <div class="common-layout">
    <Header/>
    <el-container id="container">
      <el-main>
        <div id="searchOrganize">
          <el-select v-model="cinemaObj"
                     size="large"
                     placeholder="请选择影院"
                     style="width: 360px"
                     @change="handleCinemaSelect"
                     clearable>
            <el-option
                v-for="cinema in cinemaList"
                :key="cinema.cId"
                :label="cinema.cName"
                :value="cinema.cId">
              <span style="float: left">{{ cinema.cName }}</span>
              <span style="float: right;color: var(--el-text-color-secondary); font-size: 13px;">
              {{ cinema.address }}</span>
            </el-option>
          </el-select>
          <el-select v-model="hallObj"
                     size="large"
                     placeholder="请选择影厅"
                     style="width: 360px"
                     @change="handleHallSelect"
                     clearable>
            <el-option
                v-for="hall in hallList"
                :key="hall.hId"
                :label="hall.hName"
                :value="hall.hId"
                clearable>
              <span style="float: left">{{ hall.hName }}</span>
              <span style="float: right;color: var(--el-text-color-secondary); font-size: 13px;">
              {{ hall.capacity }}</span>
            </el-option>
          </el-select>
          <el-text size="large" type="primary" tag="b" style="margin:0 20px ">观影日期</el-text>
          <el-radio-group v-model="dayRadio" size="large" @change="dayRadioChange">
            <el-radio-button border :value="day.date" v-for="day in dayList" :label="day.display"/>
          </el-radio-group>
        </div>

        <div id="organizeTableDiv">
          <el-table
              id="organizeTable"
              :data="organizeTableData"
              border
              :row-class-name="tableRowClassName"
              size="large"
              max-height="250"
              table-layout="fixed">
            <el-table-column prop="soId" label="场次id" v-if="false"/>
            <el-table-column prop="movieName" label="电影名称"/>
            <el-table-column prop="cinemaName" label="影院名称"/>
            <el-table-column prop="address" label="影院地址"/>
            <el-table-column prop="hallName" label="影厅名称"/>
            <el-table-column prop="beginTime" label="开始时间"/>
            <el-table-column prop="endTime" label="结束时间"/>
            <el-table-column prop="price" label="价格"/>
            <el-table-column prop="leftSeat" label="剩余座位"/>
            <el-table-column prop="operation" label="操作">
              <template #default="scope">
                <el-button size="small" @click="handleSelectSeat(scope.row)" type="success"
                           :disabled="isLeftSeat(scope.row)">
                  去选座
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
      <el-footer>
        <div id="commentPage">
          <el-pagination
              style="float:right"
              v-model:page-size="pageSize"
              :page-sizes="[2, 3, 4, 5]"
              :current-page="currentPage"
              :disabled="false"
              :total="totalCount"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              background layout="total, sizes, prev, pager, next, jumper"/>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>
<script setup>
import {ElNotification} from "element-plus";
import request from "@/request.js";
import {request2} from "@/request.js";
import qs from 'qs'
import {ref, reactive, onMounted} from "vue";
import {Lock, User, Cellphone, UserFilled, Search} from "@element-plus/icons-vue";
import SessionStorage from "@/SessionStorage.js";
import {useRoute, useRouter} from "vue-router";
import axios from "axios";
import moment from "moment";


const router = useRouter();
const loginUser = SessionStorage.getItem("loginUser");

const route = useRoute();
const midWith = route.params.mid;
console.log("从电影详情跳转之后，携带的mid为：" + midWith);


// 选择电影院下拉框
const cinemaObj = ref('')
const hallObj = ref('')
// 下拉框内容列表
const cinemaList = ref([{
  cId: -1,
  cName: 'Beijing',
  address: 'Beijing',
}]);
// 查询电影院列表
const cinemaAndHallList = reactive([{
  cId: -1,
  cName: "",
  address: "",
  hallList: [{
    hId: -1,
    cId: -1,
    hName: "",
    hCapacity: "",
    rowNo: -1,
    lineNo: -1,
  }]
}])

// 选中cinema之后，联动的hallList
const hallList = ref([{
  hId: -1,
  hName: '',
  capacity: '',
}])

const searchCinemaList = async () => {
  request2({
    url: "/cinema/selectAll",
    method: "post",
  }).then(res => {
    if ('200' === res.code && res.data != null) {
      console.log('查询所有电影院成功！');
      console.log('查询所有电影院接口返回的数据：', res.data);
      const cinemaAndHallListReturn = res.data;
      // 清空后端返回的影院demo数据
      cinemaAndHallList.splice(0, cinemaAndHallList.length);
      // 清空影院下拉框数据
      cinemaList.value.splice(0, cinemaList.value.length);
      cinemaAndHallListReturn.forEach(item => {
        cinemaAndHallList.push(item);
        let select = reactive({
          cId: -1,
          cName: "",
          address: ""
        })
        select.cId = item.cId;
        select.cName = item.cName;
        select.address = item.address;
        cinemaList.value.push(select);
      })
    }
  })
}
searchCinemaList();
const handleCinemaSelect = () => {
  console.log("电影院选择框发生了改变！");
  console.log("当前选中值为：" + cinemaObj.value)
  if (cinemaObj.value !== null && cinemaObj.value !== '') {
    queryDto.cid = cinemaObj.value;
    searchOrganize();
    cinemaAndHallList.forEach(item => {
      if (item.cId === cinemaObj.value) {
        // 清空影院下拉框数据
        hallList.value.splice(0, hallList.value.length);
        item.hallList.forEach(item2 => {
          let select2 = reactive({
            hId: -1,
            hName: "",
            capacity: ""
          })
          select2.hId = item2.hId;
          select2.hName = item2.hName;
          select2.capacity = "容量：" + item2.hCapacity + "个";
          hallList.value.push(select2);
        })
      }
    })
  }
}
const handleHallSelect = () => {
  console.log("影厅选择框发生了改变！");
  console.log("当前选中值为：" + hallObj.value)
  queryDto.hid = hallObj.value;
  searchOrganize();
}
const today = new moment().format('YYYYMMDD');
const dayRadio = ref(today);
const dayRadioChange = (val) => {
  console.log(">>> 日期单选的选中值改变为：" + val);
  dayRadio.value = val;
  queryDto.day = dayRadio.value;
  searchOrganize();
}

const dayList = reactive([
  {
    date: today,
    display: "今天"
  },
  {
    date: new moment().add(1, 'days').format("YYYYMMDD"),
    display: "明天"
  },
  {
    date: new moment().add(2, 'days').format("YYYYMMDD"),
    display: "后天"
  },
  {
    date: new moment().add(3, 'days').format("YYYYMMDD"),
    display: new moment().add(3, 'days').format("YYYY年MM月DD日")
  },
  {
    date: new moment().add(4, 'days').format("YYYYMMDD"),
    display: new moment().add(4, 'days').format("YYYY年MM月DD日")
  },
]);

// 场次表格
// 用于存储当前页的数据
const organizeTableData = reactive([
  {
    soId: -1,
    movieName: "误杀3",
    cinemaName: "金熊国际影城",
    hallName: "3D1号厅",
    beginTime: "2024-12-31 18:32:12",
    endTime: "2024-12-31 21:32:12",
    price: "49元",
    leftSeat: 0,
  },
  {
    soId: -1,
    movieName: "小小的我",
    cinemaName: "金鸭子国际影城",
    hallName: "巨幕2号厅",
    beginTime: "2024-12-31 12:22:20",
    endTime: "2024-12-31 14:40:11",
    price: "49元",
    leftSeat: 10,
  },
  {
    soId: -1,
    movieName: "年会不能停",
    cinemaName: "金大鹅国际影城",
    hallName: "普通3号厅",
    beginTime: "2024-12-31 12:22:20",
    endTime: "2024-12-31 14:40:11",
    price: "39元",
    leftSeat: 50,
  }
])

const isLeftSeat = (row) => {
  return row.leftSeat === 0;
};
const tableRowClassName = ({row, rowIndex}) => {
  if (row.leftSeat === 0) {
    return 'error-row'
  } else if (row.leftSeat < 20) {
    return 'warning-row'
  }
  return ''
}
// 查询场次

// 分页插件
const currentPage = ref(1);
const pageSize = ref(2);
const totalCount = ref(0);


const queryDto = reactive({
  cid: cinemaObj.value,
  hid: hallObj.value,
  mid: midWith,
  day: dayRadio.value,
  pageNo: currentPage.value,
  pageSize: pageSize.value,
})

console.log("查询场次的参数是：" + JSON.stringify(queryDto))
const searchOrganize = () => {
  request2({
    url: "/organize/selectCondition",
    method: "post",
    data: queryDto
  }).then(res => {
    if ('200' === res.code && res.data != null) {
      console.log('查询场次成功！');
      console.log('查询场次接口返回的数据：', res.data);

      totalCount.value = res.data.totalCount;
      pageSize.value = res.data.pageSize;

      organizeTableData.splice(0, organizeTableData.length);
      // 更新当前页数据
      organizeTableData.push(...res.data.list);

    } else {
      ElNotification({
        type: 'error',
        message: res.msg
      })
    }
  })
}
searchOrganize();

const handleCurrentChange = async (newPage) => {
  console.log("pageNo修改为第" + newPage + "页！");
  currentPage.value = newPage;
  queryDto.pageNo = newPage;
  searchOrganize();
};

// 处理每页显示数量改变的方法
const handleSizeChange = (newSize) => {
  console.log("pageSize修改为每页" + newSize + "条！");
  pageSize.value = newSize;
  currentPage.value = 1;

  queryDto.pageSize = newSize;
  searchOrganize();
};

const handleSelectSeat = (row) => {
  const soId = row.soId;
  console.log("购票的场次id为：" + soId);

  router.push({name: "BuyTicket", params: {soId: soId}});
}
</script>

<style scoped>


#searchOrganize {
  display: flex;
  justify-content: center;
  align-items: center;
}

#searchOrganize .el-select {
  margin: 10px 40px;
}

#organizeTableDiv {
  margin-top: 20px;
  width: 100%;
}

:deep(.el-table .warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

:deep(.el-table .error-row) {

  --el-table-tr-bg-color: var(--el-color-error-light-9);
}
</style>